pipeline {
    agent any

    environment {

        ASSET_IMAGE = 'microbeam-asset-management-v3.0'
        // SYSLOG_IMAGE = "microbeam-syslog-v3.0"

        // IMAGE_TAG = sh(script: "echo `date '+%Y%m%d-%H%M%S'`", returnStatus: true) 
        IMAGE_TAG = sh(script: "echo `date '+%Y%m%d-%H%M%S'`", returnStdout: true).trim()
        WORKDIR = '/home/ubuntu/data/docker/docker-manager/asset-v3.0'

        DOCKER_COMPOSE_FILE = "${WORKSPACE}/deployment/docker-compose.yaml"
        NGINX_CONF = "${WORKSPACE}/deployment/nginx"
    }

    stages {
        stage('Build') {
            steps {
                echo 'Building..'
                sh '''
                    docker build -t ${ASSET_IMAGE}:${IMAGE_TAG} -f deployment/Dockerfile .
                '''
                echo 'Build end'
            }
        }

        stage('Update IMAGE') {
            steps {
                echo 'Update IMAGE..'
                echo "${ASSET_IMAGE}:${IMAGE_TAG}"
                sh '''
                    echo "[INFO]: update asset manager"
                    sed -i "s~${ASSET_IMAGE}:latest~${ASSET_IMAGE}:${IMAGE_TAG}~" ${DOCKER_COMPOSE_FILE}
                    
                    # echo "[INFO]: update syslog" 
                    # sed -i "s~${SYSLOG_IMAGE}:latest~${SYSLOG_IMAGE}:${IMAGE_TAG}~" ${DOCKER_COMPOSE_FILE}
                '''
            }
        }

        stage('Deploy') {
            steps {
                echo 'Deploying....'
                sh '''
                    if [ ! -d "${WORKDIR}" ]; then 
                        mkdir -p ${WORKDIR}
                    fi 

                    if [ -f "${WORKDIR}/docker-compose.yaml" ]; then 
                        rm -f ${WORKDIR}/docker-compose.yaml  
                        cp ${DOCKER_COMPOSE_FILE} ${WORKDIR}/docker-compose.yaml
                    else 
                        cp ${DOCKER_COMPOSE_FILE} ${WORKDIR}/docker-compose.yaml 
                    fi 
                    
                    if [ -d "${WORKDIR}/nginx" ]; then 
                        rm -rf "${WORKDIR}/nginx" 
                        cp -r "${NGINX_CONF}" "${WORKDIR}"
                    else 
                        cp -r "${NGINX_CONF}" "${WORKDIR}"
                    fi 

                    cd ${WORKDIR} 
                    docker-compose stop 
                    docker-compose rm -f 
                    docker-compose up -d 
                '''
            }
        }
    }
}

